package com.zyy.joseata.interceptor.datasource;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInfo;
import org.springframework.beans.BeanUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;

/**
 * @author zhangyy
 */
public class JoSeataAutoDataSourceProxyAdvice implements MethodInterceptor, IntroductionInfo {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Method method = methodInvocation.getMethod();
        Object[] args = methodInvocation.getArguments();
        Method m = BeanUtils.findDeclaredMethod(JoSeataDataSourceProxy.class,method.getName(),method.getParameterTypes());
        if(m != null && DataSource.class.isAssignableFrom(method.getDeclaringClass())){
            System.out.println("使用了DataSourceProxy的MethodInterceptor methodName:"+method.getName());
            JoSeataDataSourceProxy dataSourceProxy = new JoSeataDataSourceProxy((DataSource) methodInvocation.getThis());
            return m.invoke(dataSourceProxy,args);
        }else{
            return methodInvocation.proceed();
        }
    }

    @Override
    public Class<?>[] getInterfaces() {
        return new Class[]{JoSeataProxyItf.class};
    }
}
